package com.iocollege.tinyframe.webapi.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.iocollege.tinyframe.common.MyBaseController;
import com.iocollege.tinyframe.common.annotation.Log;
import com.iocollege.tinyframe.common.core.AjaxResult;
import com.iocollege.tinyframe.common.core.constant.BusinessType;
import com.iocollege.tinyframe.common.core.constant.UserConstants;
import com.iocollege.tinyframe.common.core.domain.LoginUser;
import com.iocollege.tinyframe.common.core.domain.QueryPagePara;
import com.iocollege.tinyframe.common.utils.QueryParaHelper;
import com.iocollege.tinyframe.common.utils.SecurityUtils;
import com.iocollege.tinyframe.common.utils.ServletUtils;
import com.iocollege.tinyframe.common.utils.StringUtils;
import com.iocollege.tinyframe.entity.system.SysDictType;
import com.iocollege.tinyframe.entity.system.SysRole;
import com.iocollege.tinyframe.service.system.SysRoleService;
import com.iocollege.tinyframe.service.system.SysUserService;
import com.iocollege.tinyframe.service.system.impl.SysPermissionService;
import com.iocollege.tinyframe.service.system.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleApiController extends MyBaseController
{
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserService userService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")

    public AjaxResult list(String where, Integer pageNum, Integer pageSize, String sort, String desc) {

        QueryPagePara queryPagePara = QueryParaHelper.GenQuery(where, pageSize, pageNum, sort, desc);
        IPage<SysRole> list = roleService.getByPage(queryPagePara);
        return AjaxResult.success(list);
    }



    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return AjaxResult.success(roleService.getById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.save(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.getById(loginUser.getUser().getId()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {

        SysRole oldRole = roleService.getById(role.getId());
        roleService.checkRoleAllowed(role);
        oldRole.setStatus(oldRole.getStatus());
        oldRole.setUpdateBy(SecurityUtils.getUsername());

        return toAjax(roleService.updateRole(oldRole));
    }



    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {

        List<Long> longList = Arrays.asList(roleIds);
        return toAjax(roleService.removeByIds(longList));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return AjaxResult.success(roleService.selectRoleAll());
    }
}
